<%@page import="com.infolab.aims.domain.purchase.PurchaseOrder"%>
<%@ include file="/WEB-INF/views/taglib.jsp" %>


<h3>Create Issue Order for Vendor Repair</h3>	
	<form:form id="form" method="post" modelAttribute="purchaseOrder"  cssClass="simpleForm purchaseOrderForm" >
		<form:hidden path="purchaseOrderId" />
		<c:set var="newStatus" value="<%=PurchaseOrder.PURCHASEORDERSTATUS_NEW%>" />
		<c:set var="inprocessStatus" value="<%=PurchaseOrder.PURCHASEORDERSTATUS_INPROCESS%>" />
		<form:hidden path="purchaseOrderStatus" />
		<form:hidden path="accessDepartment.departmentId" />
		<form:hidden path="accessDepartment.departmentName" />
		
		<div class="action">
	  	<c:choose>
	  		<c:when test="${purchaseOrder.purchaseOrderId==null}">
	  			<button type="button" class="button positive" onclick="formSubmit()">
	  			Save
	  			</button>
	  			
	  			<a href="<c:url value="/purchaseOrder/create" />" class="button positive">Cancel</a>
	  			<a href="<c:url value="/purchaseOrder/search" />" class="button">Back</a>
	  		</c:when>
	  		<c:when test="${purchaseOrder.purchaseOrderId!=null}">
	  		
	  			<c:if test="${purchaseOrder.purchaseOrderStatus!=null && purchaseOrder.purchaseOrderStatus == newStatus}">
  				<button type="button" class="button positive" onclick="formUpdate()">
	  			Update
	  			</button>	  			
	  			</c:if>
	  			
	  			<c:if test="${purchaseOrder.purchaseOrderStatus!=null && ( purchaseOrder.purchaseOrderStatus == newStatus || purchaseOrder.purchaseOrderStatus == inprocessStatus )}">
	  			<a href="<c:url value="/purchaseOrder/close/${purchaseOrder.purchaseOrderId}" />" class="button">Close PO</a>
	  			</c:if>
	  			
	  			<a href="<c:url value="/purchaseOrder/print/${purchaseOrder.purchaseOrderId}" />" target="_blank" class="button">Print</a>
  				<button type="button" class="button positive" onclick="location.href='<c:url value="/purchaseOrder/search" />'">Back</button>
	  		</c:when>
	  	</c:choose>
	 	</div>	
	 	<div class="clear" style="height:1px">&nbsp;</div>
		<jsp:include page="/WEB-INF/views/message.jsp"></jsp:include>
<c:choose>
		<c:when test="${purchaseOrder.purchaseOrderId==null}">
		<input name="flag" id="flag" type="hidden" value="false"/>	
		</c:when>

		<c:otherwise>
		<input name="flag" id="flag" type="hidden" value="true"/>	
		</c:otherwise>
		</c:choose>
	  	<fieldset>
	  		<legend>Create Issue Order for Vendor Repair</legend>
	  		<div class="span-11">
				  		<aims:column cssErrorClass="error" path="purchaseOrderCode" >
				  		<form:label path="purchaseOrderCode">
				  			PO Code * 
				 		</form:label>
				  		<form:input path="purchaseOrderCode" /> <form:errors path="purchaseOrderCode"  cssClass="errorSimple" /> 
						</aims:column>
			
			
						<aims:column cssErrorClass="error" path="vendor" >
				  		<form:label path="vendor">
				  			Vendor 
				 		</form:label>	  	
				 			
				  		<form:select id="vendorId" path="vendor.vendorId" class="vendorId">
				 			<form:option value=""></form:option>
				 			<form:options items="${repairVendorList}" itemValue="vendorId" itemLabel="vendorName" />
				 		</form:select>		  	
				  		
				  		<form:errors path="vendor"  cssClass="errorSimple" /> 
						</aims:column>
						
						<aims:column cssErrorClass="error" path="assetType" >
				  		<form:label path="assetType">
				  			Asset Type
				 		</form:label>
				 		<c:set var="isvisible" value="${1 == 1}" />
				 		<form:select path="assetType" id="assetType" disabled="${isvisible}">
				 			<form:options items="${globalAssetType}" itemValue="systemCode1" itemLabel="systemCodeValueDescription" />
				 		</form:select>
				  		 <form:errors path="assetType"  cssClass="errorSimple" />	 
						</aims:column>
						
						
						<aims:column cssErrorClass="error" path="location" >
				  		<form:label path="location">
				  			From Location
				 		</form:label>
				  		<form:select id="locationId" path="location.locationId" class="locationId">
				 			<form:options items="${globalLocation}" itemValue="locationId" itemLabel="locationName" />
				 		</form:select>
				 		<form:errors path="location"  cssClass="errorSimple" /> 
						</aims:column>	
						
						<aims:column cssErrorClass="error" path="companyCode">
				  		<form:label path="companyCode">
				  			Company Code
				 		</form:label>	
				 		<form:select id="companyCode" path="companyCode" class="companyCode">
				 			<form:options items="${globalCompanyCode}" itemValue="systemCode1" itemLabel="systemCodeValueDescription" />
				 		</form:select>
				  		 <form:errors path="companyCode"  cssClass="errorSimple" />	 
						</aims:column>							
			
			</div>	
				
			<div class="span-11">
				
						<aims:column cssErrorClass="error" path="purchaseOrderDate" >
				  		<form:label path="purchaseOrderDate">
				  			PO Date  * 
				 		</form:label>
				  		<form:input path="purchaseOrderDate" id="poDate" onkeypress="return restrictCharacters(this, event, validChars);"/> 
				  		<input id="poDate_button" type="button" class="calendarBtn" />
				  		<form:errors path="purchaseOrderDate"  cssClass="errorSimple" /> 
						</aims:column>
						
						
						<aims:column cssErrorClass="error" path="purchaseOrderType" >
				  		<form:label path="purchaseOrderType">
				  			PO Order Type
				 		</form:label>
		  				
		  				<form:select id="purchaseOrderType" path="purchaseOrderType" class = "purchaseOrderType">
		  				<c:forEach items="${poTypeMap}" var="poTypeMap">
					        <option value="${poTypeMap.key}" <c:if test="${purchaseOrder.purchaseOrderType==poTypeMap.key}">selected</c:if>>
					        ${poTypeMap.value}
					        </option>
					    </c:forEach>		  				
				 		</form:select>
		  				<form:errors path="purchaseOrderType"  cssClass="errorSimple" /> 
						</aims:column>
						
		  				
		  				
		  				<c:if test="${purchaseOrder.accessDepartment.departmentId!=null}">
		  				<p class="span-11">
		  				<label>
	  					Access Department  
	 					</label> 					
	 					<c:out value="${purchaseOrder.accessDepartment.departmentName}"/>
		  				</p>
		  				</c:if>
		  				
		  				
		  				  				
		  				<c:if test="${purchaseOrder.purchaseOrderId!=null}">
						<p class="span-11">
						<label>
				  			PO Status 
				 		</label>
				 		<c:out value="${purchaseOrder.purchaseOrderStatus}" />
				 		</p> 
						</c:if>
						
		  				
		  				<p class="span-11">	
		  				<a class="button positive right" onclick="popUp()">
			  			 Map Asset to Vendor
			  			</a>
						</p>
						
		  				
		  				</div>
			
			</fieldset>
			
			<fieldset>
			
			<legend>Asset Info</legend>
		
			
			<div class="span-8 minLabel">
	  		<p class="clearfix">
	  		<label> Asset Model</label>
		  	<select name="assetModelId" id="assetModelId">
		  	</select>	
		  	</p>	
		  		  	
		  <p class="clearfix">
		  	<label>Serial No </label> 
	  		<input name="serialNo" id= "serialNo" type="text" />
	  		</p>
	  		
	  	
		  	<p class="clearfix">
	  		<a onclick="searchSerialNo()" class="button"> Search </a>	  		
	  		</p>
	  		
	  		<table id="inputs" class="gridSearch">
	  		<thead>
	  				<tr>
	  					<th title="Click below hyperlink to add to list"> + Add To List</th>
	  				</tr>
	  			</thead>
			<tbody>
	  		</tbody>
	  		</table>
	  		
			</div>
			
			<div class="span-14 last">	  		
	  	
	  	
	  
		
	  		<table id="assetTable" class="gridSearch">
	  		
	  		<caption id="header" class="captionLeft">Total number of items : 
		  		<span id="totalItems"></span></caption>
	  			<thead>
	  				<tr>
	  				    <th>Remove</th>
	  					<th>Asset Model</th>	  					
	  					<th>Serial Number</th>
	  					<th>Remarks</th>
	  					
	  					
	  				</tr>
	  			</thead>
	  			
	  			<tbody>
	  			<c:forEach items="${purchaseOrder.purchaseOrderRepairs}" var="item" varStatus="status">
	  			<c:choose>
	  			<c:when test="${item.purchaseOrderRepairId==null}">
	  			<tr class="new">
	  			</c:when>
	  			<c:otherwise>
	  			<tr>
	  			</c:otherwise>
	  			</c:choose>	  				
	  					
	  						<input name="purchaseOrderRepairs[${status.index}].purchaseOrderRepairId" type="hidden" value="${item.purchaseOrderRepairId}" />
	  						<input name="purchaseOrderRepairs[${status.index}].deleted" type="hidden" value="${item.deleted}"  class="deleted"/>
	  						<input name="purchaseOrderRepairs[${status.index}].repairStatus" type="hidden" value="${item.repairStatus}"/>
							<input name="purchaseOrderRepairs[${status.index}].purchaseOrder.purchaseOrderId" type="hidden" value="${item.purchaseOrder.purchaseOrderId}" />
	  						<input name="purchaseOrderRepairs[${status.index}].assetModel.assetModelId" type="hidden" value="${item.assetModel.assetModelId}"/>
	  						<input name="purchaseOrderRepairs[${status.index}].assetModel.assetModelName" type="hidden" value="${item.assetModel.assetModelName}"/>
							<input name="purchaseOrderRepairs[${status.index}].serialNo" type="hidden" value="${item.serialNo}" class="serialNo"/>
	  					
	  					<td>
	  					
	  						<!--<a href="#" onclick="removeRow(this)">-</a>
	  					
	  					-->
	  					<a href="javascript:void(0)" onclick="removeRow(this)" title="Delete Row">
	  						<img align="absmiddle" src="${imageUrl}/icon_delete.png">
	  					</a>
	  					
	  					</td>		  						
	  					
	  					<td>
	  					<c:out value="${item.assetModel.assetModelName}" />
	  					</td>
					  	  				
						<td>	  	
					  	<c:out value="${item.serialNo}" />
					  	</td> 
					  	
	  	
	  					<td>
	  					<input name="purchaseOrderRepairs[${status.index}].purchaseOrderRemarks" type="text" value="${item.purchaseOrderRemarks}" size="15"
	  					class="purchaseOrderRemarks" />	  					
	  					</td>
	  						  										 
	  					</tr>
	  					
	  			</c:forEach>
	  			</tbody>
	  		</table>
	  
	  		</div>
			
			</fieldset>
			
      <div class="action">
	  	<c:choose>
	  		<c:when test="${purchaseOrder.purchaseOrderId==null}">
	  			<button type="button" class="button positive" onclick="formSubmit()">
	  			Save
	  			</button>
	  			
	  			<a href="<c:url value="/purchaseOrder/create" />" class="button positive">Cancel</a>
	  			<a href="<c:url value="/purchaseOrder/search" />" class="button">Back</a>
	  		</c:when>
	  		<c:when test="${purchaseOrder.purchaseOrderId!=null}">
	  		
	  			<c:if test="${purchaseOrder.purchaseOrderStatus!=null && purchaseOrder.purchaseOrderStatus == newStatus}">
  				<button type="button" class="button positive" onclick="formUpdate()">
	  			Update
	  			</button>	  			
	  			</c:if>
	  			
	  			<c:if test="${purchaseOrder.purchaseOrderStatus!=null && ( purchaseOrder.purchaseOrderStatus == newStatus || purchaseOrder.purchaseOrderStatus == inprocessStatus )}">
	  			<a href="<c:url value="/purchaseOrder/close/${purchaseOrder.purchaseOrderId}" />" class="button">Close PO</a>
	  			</c:if>
	  			
	  			<a href="<c:url value="/purchaseOrder/print/${purchaseOrder.purchaseOrderId}" />" target="_blank" class="button">Print</a>
  				<button type="button" class="button positive" onclick="location.href='<c:url value="/purchaseOrder/search" />'">Back</button>
	  		</c:when>
	  	</c:choose>
	 </div>	
	
	
	<table id="searchSection" style="visibility:hidden" class="gridSearch">
	<tbody>
		<p class="span-5">
		<tr>
	  	<td>
	  	<!--<a class="CD_addNew addRow" href="javascript:void(0)" onclick="addRow(this)" title="Add Row">
	  	<img align="absmiddle" src="${imageUrl}/icon_add.png"> <span class="serialNo">
	  	</a>-->
	  	
	  	<a href='javascript:void(0)' onclick='addRow(this)'><span class="serialNo"></span></a>
	  		
	  	<!--<a onclick="addRow(this)" class="button positiveDark">+ <span class="serialNo"></span> </a>	  		  	
	  	-->
	  	<input name="serialNo" type="hidden" />
	  	<input name="assetModelId" type="hidden" />
	  	<input name="assetModelName" type="hidden" />
	  	
	  	</td>	  	
		</tr>
		</p>
		</tbody>
	</table>
	
	
	<table id="tmpTable_1" style="visibility:hidden">
		<tr class="new">
		
		<input name="purchaseOrderRepairs.purchaseOrderRepairId" type="hidden" />
		<input name="purchaseOrderRepairs.deleted" type="hidden" class="deleted"/>
		<input name="purchaseOrderRepairs.purchaseOrder.purchaseOrderId" type="hidden" value="${purchaseOrder.purchaseOrderId}" />
		<input name="purchaseOrderRepairs.assetModel.assetModelId" type="hidden" />
		<input name="purchaseOrderRepairs.assetModel.assetModelName" type="hidden" />
		<input name="purchaseOrderRepairs.serialNo" type="hidden" class="serialNo" />
		 <td> 	
	  		<!--<a onclick="removeRow(this)">-</a>
	  	-->
	  	
	  	<a href="javascript:void(0)" onclick="removeRow(this)" title="Delete Row">
	  						<img align="absmiddle" src="${imageUrl}/icon_delete.png">
	  					</a>
	  					
	  	</td>
	  	
	  	<td>	  	
	  	<span class="assetModelName"></span>	  	
	  	</td> 	
	  	  				
		<td>	  	
	  	<span class="serialNo"></span>	  	
	  	</td> 
	  	
			  	
	 	 <td>
	  	<input name="purchaseOrderRepairs.purchaseOrderRemarks" type="text" size="15"   class="purchaseOrderRemarks" />
	  	</td>	  	
	  	  	
	  	
		</tr>
	</table>
	
	</form:form>
	  
	<script type="text/javascript" src="<spring:url value="/resources/js/select-option-disabled-emulation.js" />"></script>
	<script type="text/javascript" src="<spring:url value="/resources/js/restrictCharactersForDateInput.js" />"></script>
	<script type="text/javascript">
		var validChars = /[1234567890-]/g; 
		var finalValidRowCount = 0;
		var assetModelPurchaseOrder;
		var assetModelEquip = new Array();
		
		$(document).ready(function() {
			cal = Calendar.setup({
		          onSelect: function(cal) { cal.hide() },
		          showTime: false
		      });
			var at = $('#assetTable tbody tr');
			if(at){
			finalValidRowCount = at.size();
			}
			hideHiddenRows();
			
			if(finalValidRowCount<=0){
				$('#header').hide();				
			}
			else{			
				$('#header').show();
				$('#totalItems').text(finalValidRowCount);
			}
			
			
			rebuiltCalendar();
			checkPOTypeDropDown();
			populateList();
			
		});
		
		function hideHiddenRows()
		{			
		var table = $(' #assetTable tbody tr');
			
			var hiddenRow=false;
			table.each(
					function () {
						
					hiddenRow = $('.deleted',this).val();
					var modelId = $('.assetModelId',this).val();
					
					///alert(hiddenRow);
						if(hiddenRow=='true'){
							$(this).hide();
							finalValidRowCount--;
							//removeInContain(componentSet,modelId);
						}
					}
					);
			
		}
		
		
		
		
		function populateList()
		{
			
			var assetType =  $('#assetType').val();
			var vendorId =  $('#vendorId').val();
			$('#assetModelId option').remove();
			if(assetType!="" && vendorId!=""){
					$.getJSON("<c:url value="/ajax/vendorPrice"></c:url>?vendorId="+vendorId+"&assetType="+assetType, function(data) {
						  
						  	
							 assetModelEquip = new Array();
								assetModelPurchaseOrder = data;
								for(i=0;i<data.length;i++)
								{
									if(assetModelPurchaseOrder[i].assetType == "EQUIPMENT"){
										assetModelEquip.push(assetModelPurchaseOrder[i]);
									}
								}
								
							  for(var i=0;i<assetModelEquip.length;i++)
								{
									$('#assetModelId').
							          append($("<option></option>").
							          attr("value",assetModelEquip[i].assetModelId).
							          text(assetModelEquip[i].assetModelName));
									
								}
							  
					});
			}
		}
		
		
		$('#assetType').change(function() {
			  populateList();
		
			});
		

		$('.vendorId').change(function() {
			populateList();
			
			});
		
		
		$('.purchaseOrderType').change(function(){
			var purchaseOrderType =  $('#purchaseOrderType').val();
			
			var url = "<c:url value="/purchaseOrder/creates"/>";
			
			var form = $('#form');				
			redirect(form,url);
						
			
		});
		
		function redirect(form,url){
			form.attr('action',url );
			
			form.submit();
		}
		
		function formSubmit(){
		if(validateForm()){
			var url = "<c:url value="/purchaseOrder/create"/>";
			var form = $('#form');				
			redirect(form,url);
			}
		}
		
		function formUpdate(){
			if(validateForm()){
			var url = "<c:url value="/purchaseOrder/update/${purchaseOrder.purchaseOrderId}"/>";
			var form = $('#form');				
			redirect(form,url);
			}
		}
		
		function validateForm(){
			var res = true;
			
			if(finalValidRowCount<=0){
				alert(" Pls do update the details to start processing purchase order");
				res = false;
				return res;
			}			
			return res;
		}
		

	function searchSerialNo(){
		
			var serialNoIds = new Array();
			var assetModelId =  $('#assetModelId').val();
			var serialNo =  $('#serialNo').val();
			var locationId = $('#locationId').val();
			var companyCode = $('#companyCode').val();
			
			
					$.getJSON("<c:url value="/ajax/equipment/faulty"></c:url>?assetModelId="+assetModelId+"&serialNo="+serialNo+"&locationId="+locationId+
																"&companyCode="+companyCode, function(data) {
						for(i=0;i<data.length;i++){
							serialNoIds.push(data[i]);
						}
						if(data.length <=0 )
						{
						 alert('No faulty equipment is found for the  given search scenario');
						}
						
						populateAddButton(serialNoIds);
					});
		}
		
	function populateAddButton(serialNoIds){
		
		//$('#inputs tbody tr').remove();
		
		var inputs =$('#inputs tbody') ; 
		inputs.html('');
		
		var existingSerialNo = $('input.serialNo');
		var arrSerialNo = new Array();
		if(existingSerialNo )
		{
			existingSerialNo.each(function(data){
				if($(this).val()!='' && $(this).parent().is(':visible'))
					arrSerialNo.push($(this).val());
			});
		}
			
		for(var i=0;i<serialNoIds.length;i++){
			
			if($.inArray(serialNoIds[i].assetEquipmentPK.serialNo,arrSerialNo)==-1){
			var row = $('#searchSection tr').clone();
			$('input[name=serialNo]',row).val(serialNoIds[i].assetEquipmentPK.serialNo);
			$('.serialNo',row).text(serialNoIds[i].assetEquipmentPK.serialNo);
			$('input[name=assetModelId]',row).val(serialNoIds[i].assetEquipmentPK.assetModel.assetModelId);
			$('input[name=assetModelName]',row).val(serialNoIds[i].assetEquipmentPK.assetModel.assetModelName);
			row.appendTo('#inputs tbody');
			}
		}
		
	}
		
	
		
		function rebuiltCalendar()
		{
			cal.manageFields("poDate_button", "poDate", globalJsCalDateFormat);			
			  
		}
		
		function validateVendor()
		{
			var vendorId =  $('#vendorId').val();
			if(vendorId==''){
				alert('Vendor is a mandatory field to start processing Purchase Order');
				return false;
			}
			var locationId = $('#locationId').val();
				if(locationId==''){
					alert('Location is a mandatory field to start processing Purchase Order');
					return false;
				}
				
		return true;
			
		}
		
		function addRow(obj)
		{
			
			if(validateVendor())
			{
			var row = $('#tmpTable_1 tr').clone();
			var rowSize = $('#assetTable tbody tr').size();			
			
			$('input[name=purchaseOrderRepairs.purchaseOrderRepairId]',row).attr('name','purchaseOrderRepairs['+rowSize+'].purchaseOrderRepairId');
			$('input[name=purchaseOrderRepairs.purchaseOrder.purchaseOrderId]',row).attr('name','purchaseOrderRepairs['+rowSize+'].purchaseOrder.purchaseOrderId');
			
			$('input[name=purchaseOrderRepairs.deleted]',row).attr('name','purchaseOrderRepairs['+rowSize+'].deleted').val(false);
			var tmpRow = $(obj).parent();
			var assetModelId = $('input[name=assetModelId]',tmpRow).val();	
			var serialNo = $('input[name=serialNo]',tmpRow).val();
			var assetModelName = $('input[name=assetModelName]',tmpRow).val();
			
			//var purchaseOrderRemarks = $('#purchaseOrderRemarks').val();
						
							
			$('input[name=purchaseOrderRepairs.assetModel.assetModelId]',row).attr('name','purchaseOrderRepairs['+rowSize+'].assetModel.assetModelId').val(assetModelId);
			$('input[name=purchaseOrderRepairs.assetModel.assetModelName]',row).attr('name','purchaseOrderRepairs['+rowSize+'].assetModel.assetModelName').val(assetModelName);
			$('.assetModelName',row).text(assetModelName);
			$('input[name=purchaseOrderRepairs.serialNo]',row).attr('name','purchaseOrderRepairs['+rowSize+'].serialNo').val(serialNo);
			$('span.serialNo',row).text(serialNo);
			$('input[name=purchaseOrderRepairs.purchaseOrderRemarks]',row).attr('name','purchaseOrderRepairs['+rowSize+'].purchaseOrderRemarks');
			row.appendTo('#assetTable tbody');
			$(obj).parent().parent().hide();			
			checkPOTypeDropDown();
			finalValidRowCount++;
			$('#totalItems').text(finalValidRowCount);
			$('#header').show();
			}
			
		}
		
		function removeRow(obj)
		{
			var ctx = $(obj).parent().parent();
			
				$('input[name*=deleted]',ctx).val('true');
				ctx.hide();
		
			checkPOTypeDropDown();
			finalValidRowCount--;
			$('#totalItems').text(finalValidRowCount);
			$('#header').show();
		}
		
		function checkPOTypeDropDown(){
			
			var assetTable = $('#assetTable tbody tr');
			var flag =  $('#flag').val();
			if(assetTable){
			
				
					if(assetTable.size()>0){
						$("#purchaseOrderType option").not(":selected").attr("disabled",true);
						//if(flag == 'true'){
						$("#vendorId option").not(":selected").attr("disabled",true);
						$("#locationId option").not(":selected").attr("disabled",true);
						$("#companyCode option").not(":selected").attr("disabled",true);
						
						emulate(document.getElementById('vendorId'));
						emulate(document.getElementById('locationId'));
						
						//}
					}
					else{
						$("#purchaseOrderType option").not(":selected").attr("disabled",false);
					}
					
					emulate(document.getElementById('purchaseOrderType'));
					emulate(document.getElementById('companyCode'));
			}
		}
		
		function popUp(){
			var vendorId =  $('#vendorId').val();
			
			if(validate(vendorId)){			
				var url = "<c:url value="/vendor/updateAssets/"></c:url>"+vendorId+"?popUpFlag=Y";
				openPopUp(url);								
			}			
		}
		
		function validate(vendorId) {
			
			if(vendorId==''){
				alert('Pls do select vendor to map asset');
				return false;
			}
			
			return true;
		}
		
		 function openPopUp(url)  
		 {  
		  newwindow = window.open(url,'_blank',"height=500,width=1100,resizable=yes,scrollbars=yes");  
		  newwindow.focus() ;
		 } 
		 
		 function reloadParent()
		 {			 
			 setTimeout('refresh()', 50);			
		 }
		 
		 function refresh() {
			
			 if (!newwindow || newwindow.closed) {
				 populateList();
			 }
		 }
		
		
			
	</script>
